import axios from 'axios';
import { getToken } from '@/utils/store';
import router from '@/router';

const http = axios.create({
  baseURL: '/api/',
  timeout: 5000,
});

export default {
  get(url) {
    return new Promise((resolve, reject) => {
      http({
        url,
        headers: {
          'Authorization' : `Bearer ${getToken()}`
        }
      })
        .then((res) => {
          if (res.data.msg == '权限不足') {
            window.$message.info(
              '身份失效，请重新登录！'
            );
            return router.push({
              path: '/authorization'
            });
          }
          return resolve(res.data);
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
          resolve({
            code: 500,
            msg: '服务超时，请重试！'
          });
        });
    });
  },
  post(url, data) {
    return new Promise((resolve, reject) => {
      http.post(url,data,{
        headers: {
          'Authorization' : `Bearer ${getToken()}`
        }
      })
        .then((res) => {
          if (res.data.msg == '权限不足') {
            window.$message.info(
              '身份失效，请重新登录！'
            );
            return router.push({
              path: '/authorization'
            });
          }
          return resolve(res.data);
        })
        .catch(function (error) {
          // 处理错误情况
          console.log(error);
          resolve({
            code: 500,
            msg: '服务超时，请重试！'
          });
        });
    });
  },
};